package com.zheng.common.util;


import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 代码生成类
 * Created by likun on 2017/12/28.
 */
public class MybatisGeneratorUtil {


    /**
     * 根据模板生成generatorConfig.xml文件
     *
     * @param jdbc_driver   驱动路径
     * @param jdbc_url      链接
     * @param jdbc_username 帐号
     * @param jdbc_password 密码
     * @param module        项目模块
     * @param database      数据库
     * @param table_prefix  表前缀
     * @param package_name  包名
     */
    public static void generator(
            String jdbc_driver,
            String jdbc_url,
            String jdbc_username,
            String jdbc_password,
            String module,
            String database,
            String table_prefix,
            String package_name) throws Exception {


        String targetProject = module + "/" + module + "-dao";
        String basePath = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "").replace(targetProject, "").replaceFirst("/", "");

        targetProject = basePath + targetProject;
        String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "' AND table_name LIKE '" + table_prefix + "_%';";

        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir("D://codeGen");
        gc.setAuthor("likun");

        gc.setActiveRecord(false);
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("转换类型：" + fieldType);
                // 注意！！processTypeConvert 存在默认类型转换，如果不是你要的效果请自定义返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName(jdbc_driver);
        dsc.setUsername(jdbc_username);
        dsc.setPassword(AESUtil.AESDecode(jdbc_password));
        dsc.setUrl(jdbc_url);

        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        //strategy.setTablePrefix(table_prefix);// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略

        // 查询定制前缀项目的所有表
        List<String> tableNames = new ArrayList<>();
        JdbcUtil jdbcUtil = new JdbcUtil(jdbc_driver, jdbc_url, jdbc_username, AESUtil.AESDecode(jdbc_password));
        List<Map> result = jdbcUtil.selectByParams(sql, null);
        result.forEach((map) -> tableNames.add(map.get("TABLE_NAME").toString()));
        jdbcUtil.release();
        String[] tableNameArray = new String[tableNames.size()];
        // 需要生成的表
        strategy.setInclude(tableNames.toArray(tableNameArray));

        strategy.setSuperServiceClass("com.zheng.common.base.BaseService");
        strategy.setSuperServiceImplClass("com.zheng.common.base.BaseServiceImpl");
        strategy.setSuperControllerClass("com.zheng.common.base.BaseController");
        strategy.setSuperEntityClass("com.zheng.common.base.BaseEntity");
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(package_name);
        pc.setEntity("dao.model");
        pc.setMapper("dao.mapper");
        pc.setXml("dao.mapper");
        pc.setService("rpc.api");
        pc.setServiceImpl("rpc.service.impl");
        pc.setController("admin.controller");

        mpg.setPackageInfo(pc);

        // 注入自定义配置，可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {

            }
        };
        String modelPath = basePath + module + "/" + module + "-dao" + "/src/main/java/" +
                package_name.replaceAll("\\.", "/") + "/dao/model";
        String mapperPath = basePath + module + "/" + module + "-dao" + "/src/main/java/" +
                package_name.replaceAll("\\.", "/") + "/dao/mapper";
        String xmlPath = basePath + module + "/" + module + "-rpc-service" + "/src/main/java/" +
                package_name.replaceAll("\\.", "/") + "/dao/mapper";
        String servicePath = basePath + module + "/" + module + "-rpc-api" + "/src/main/java/" +
                package_name.replaceAll("\\.", "/") + "/rpc/api";
        String serviceImplPath = basePath + module + "/" + module + "-rpc-service" + "/src/main/java/" +
                package_name.replaceAll("\\.", "/") + "/rpc/service/impl";
        List<FileOutConfig> focList = new ArrayList<>();
        //调整entity生成目录
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return modelPath + "/" + tableInfo.getEntityName() + ".java";
            }
        });

        //调整maper生成目录
        focList.add(new FileOutConfig("/templates/mapper.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return mapperPath + "/" + tableInfo.getMapperName() + ".java";
            }
        });

        //调整service生成目录
        focList.add(new FileOutConfig("/templates/service.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return servicePath + "/" + tableInfo.getServiceName() + ".java";
            }
        });

        //生成serviceMock降级实现类
        focList.add(new FileOutConfig("/templates/serviceMock.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return servicePath + "/" + tableInfo.getServiceName() + "Mock.java";
            }
        });

        //调整serviceImpl生成目录
        focList.add(new FileOutConfig("/templates/serviceImpl.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return serviceImplPath + "/" + tableInfo.getServiceImplName() + ".java";
            }
        });

        // 调整 xml 生成目录
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return xmlPath + "/" + tableInfo.getXmlName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 执行生成
        mpg.execute();
    }

}
